import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import services from '@/services/demo';
import { Button, Divider, Drawer, Input, message, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import ModalCard from '@/components/ModalCard';
import { dateFormat } from './../../utils/format';
import WangEditor from '@/components/WangEditor';
import { remove } from '@/services/demo/AnnounceController';

const { queryList, add, modify, removeById } =
  services.AnnounceController;

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.AnnounceType) => {
  const hide = message.loading('正在添加');
  try {
    await add({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: Partial<API.AnnounceType>) => {
  const hide = message.loading('正在修改');
  try {
    await modify(fields);
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};

const handleRemove = async (id: string) => {
  const hide = message.loading('正在删除');
  try {
    await removeById(id);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const handleRemoveSelected = async (selectedRows: API.AnnounceType[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await remove({
      ids: selectedRows.map(it => parseInt(it.anId)) || []
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


function AnnouncePage() {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] =
    useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState<API.AnnounceType | {}>({});
  const actionRef = useRef<ActionType>();
  const [row, setRow] = useState<API.AnnounceType>();
  const [selectedRowsState, setSelectedRows] = useState<API.AnnounceType[]>([]);

  const columns: ProColumns<API.AnnounceType>[] = [
    {
      title: 'ID',
      width: 70,
      dataIndex: 'anId',
      tip: 'id是唯一的 key',
      hideInSearch: true,
      renderFormItem: () => <Input disabled/>
    },
    {
      title: '公告标题',
      width: 200,
      dataIndex: 'anTitle',
      valueType: 'text',
    },
    {
      title: '时间',
      width: 100,
      dataIndex: 'anTime',
      hideInSearch: true,
      hideInForm: true,
      render(_, record) {
        return (
          <span>{dateFormat(record.anTime)}</span>
        )
      }
    },
    {
      title: '内容',
      dataIndex: 'anContent',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '操作',
      width: 160,
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => (
        <>
          <Button type='primary'
            onClick={() => {
              setStepFormValues((_: any) => ({ ...record }));
              handleUpdateModalVisible(true);
            }}
          >
            修改
          </Button>
          <Divider type="vertical" />
          <Popconfirm
            title="确定要删除吗？"
						onConfirm={async () => {
              const success = await handleRemove(record.anId)
              if (success) {
                actionRef.current?.reloadAndRest?.()
              }
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button type='primary' danger >删除</Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '公告管理',
      }}
    >
      <ProTable<API.AnnounceType>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="anId"
        scroll={{ x: 1600 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => handleModalVisible(true)}
          >
            新建
          </Button>,
        ]}
        request={queryList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={async () => {
              await handleRemoveSelected(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button>批量删除</Button>
          </Popconfirm>
        </FooterToolbar>
      )}
      <ModalCard
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable<API.AnnounceType, API.AnnounceType>
          onSubmit={async (value) => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="anId"
          type="form"
          columns={columns}
        />
      </ModalCard>
      {stepFormValues && Object.keys(stepFormValues).length > 0 ?
        <ModalCard
          onCancel={() => {
            handleUpdateModalVisible(false)
            setStepFormValues({})
          }}
          modalVisible={updateModalVisible}
        >
          <ProTable<API.AnnounceType, API.AnnounceType>
            form={{initialValues:stepFormValues}}
            onSubmit={async (value) => {
              const success = await handleUpdate(value);
              if (success) {
                handleUpdateModalVisible(false);
                setStepFormValues({})
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            rowKey="anId"
            type="form"
            columns={columns}
          />
        </ModalCard>
        : null
      }

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.anId && (
          <ProDescriptions<API.AnnounceType>
            column={2}
            title={row?.anId}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.anId,
            }}
            columns={columns as ProDescriptionsItemProps<API.AnnounceType>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
}

export default AnnouncePage;